package com.llstudio.jpa.service;

import com.llstudio.jpa.entity.Customer;
import jakarta.persistence.*;

import java.sql.Timestamp;
import java.util.List;

public class BusinessService2 {

    public static EntityManagerFactory entityManagerFactory;

    static {
        entityManagerFactory = Persistence.createEntityManagerFactory("jpa-entity-definition");
    }

    public void findAllCustomers() {
        try (EntityManager entityManager = entityManagerFactory.createEntityManager()) {
            EntityTransaction tx = entityManager.getTransaction();
            tx.begin();
            TypedQuery<Customer> query = entityManager.createQuery("from Customer as c order by c.name asc", Customer.class);
            List<Customer> customers = query.getResultList();
            for (Customer customer : customers) {
                System.out.println(customer);
            }
            tx.commit();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void saveCustomer(Customer customer) {
        try (EntityManager entityManager = entityManagerFactory.createEntityManager()) {
            EntityTransaction tx = entityManager.getTransaction();
            tx.begin();
            entityManager.persist(customer);
            tx.commit();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        Customer customer1 = new Customer();
        customer1.setName("Diane");
        customer1.setMarried(true);
        customer1.setRegisteredTime(new Timestamp(System.currentTimeMillis()));
        BusinessService2 service2 = new BusinessService2();
        service2.saveCustomer(customer1);
        service2.findAllCustomers();
        entityManagerFactory.close();
    }
}
